import { Component, OnInit, HostBinding } from '@angular/core';
import { Router } from '@angular/router';
import { Subject } from 'rxjs';
import { debounceTime, scan } from 'rxjs/operators';

import { PickerService, ToastService } from 'ngx-weui';

import { routerTransition } from '../shared/animation/routerTransition';
import { DataStorageService } from '../data-storage.service';


import * as moment from 'moment';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
  animations: [
    routerTransition,
  ]
})
export class HomeComponent implements OnInit {
  @HostBinding('@routeAnimation') routeAnimation = true;
  @HostBinding('style.display') display = 'block';
  @HostBinding('style.position') position = 'relative';


  count: number = 0;    // 记录用户点击多少次
  ppx = new Subject();
  ppx$;


  workTime;   // 上下班时间
  isHoliday:boolean = false;    // 是否放假时间,如果是放假时间则不进行下班时间计算

  startWork;      //上班时间
  startLunchBreak;    // 开始午休
  endLunchBreak;      //午休结束
  endWork;        // 下班
  isDoubleBreak;  //是否双休

  nextEndWork;      // 下一个下班时间
  nextWeekend;   // 下一个放假时间

  workCountdown;    // 下班倒计时,用于显示距离下班时间
  weekendCountdown; // 放假倒计时,用于显示距离放假时间

  workCountdownTimer;
  weekendCountdownTimer;


  constructor(
    private srv: PickerService,
    private toast: ToastService,
    private router: Router,
    private dataStorageService: DataStorageService
  ) { }

  ngOnInit() {
    this.workTime = this.dataStorageService.getLocal('workTime') ? JSON.parse(this.dataStorageService.getLocal('workTime')) : null;
    // 计算下班倒计时
    if (this.workTime === null) {
      // 如果没有设置过上下班时间则跳转到设置页面
      this.router.navigate(['/setting']);
      return;
    }

    this.startWork = this.workTime.startWork.time;
    this.startLunchBreak = this.workTime.startLunchBreak.time;
    this.endLunchBreak = this.workTime.endLunchBreak.time;
    this.endWork = this.workTime.endWork.time;
    this.isDoubleBreak = this.workTime.isDoubleBreak;

    console.log(`
      上班: ${this.startWork}\n
      午休开始: ${this.startLunchBreak}\n
      午休结束: ${this.endLunchBreak}\n
      下班: ${this.endWork}\n
      ${this.isDoubleBreak ? '双休' : '单休'}
    `)

    const weekend = this.isDoubleBreak ? 5 : 6;
    // 计算本周放假时间
    this.nextWeekend = moment().isoWeekday(weekend).set({
      'hours': this.workTime.endWork.hours,
      'minutes': this.workTime.endWork.minutes,
      'seconds': this.workTime.endWork.seconds
    });

    this.calcWeekend(this.nextWeekend);   // 开始执行计算本周放假时间



    // 处理下班时间数据
    const workTimes = [
      {
        start: moment(this.startWork,'HH:mm:ss'),
        end: moment(this.startLunchBreak,'HH:mm:ss')
      },
      {
        start: moment(this.endLunchBreak,'HH:mm:ss'),
        end: moment(this.endWork,'HH:mm:ss') 
      }
    ];
    this.calcWork(workTimes);




    // 订阅用户点击事件
    this.ppx$ = this.ppx.pipe(
      debounceTime(500),
      scan(count => count + 1, 0)
    ).subscribe(
      count => {
        console.log(count)
        if (count === 5) {
          this.toast.loading(`点击次数过多,正在关机...`, 2000);
          setTimeout(() => {
            this.toast.success(`让你皮！吓到了吧！`, 1000);
          }, 2000);
        }
      }
    )
  }


  
  /**
   * 计算距离下一个时间的倒计时,时间可以有多个,每个时间包含开始和结束
   *
   * @param {Array<{start,end}>} times
   * @memberof HomeComponent
   */
  calcWork(times:Array<{start,end}>){
    if(this.workCountdownTimer) clearInterval(this.workCountdownTimer);
    this.workCountdown = `00:00:00`;
    this.workCountdownTimer = setInterval(() => {
      const currentTime = times.filter(time => {
        return moment().isBetween(time.start,time.end)
      });
      if(!currentTime.length || !this.isHoliday){
        this.workCountdown = `00:00:00`;
        return;
      }
      const ms = currentTime[0].end.diff(moment());
      const duration = moment.duration(ms);
      this.workCountdown = `${duration.hours()}:${duration.minutes()}:${duration.seconds()}`;
    }, 1000);
  }


  /**
   * 计算距离下一次放假时间,基于设置了上下班时间为准
   * 
   * @param {number} nextWeekend  - 下一个放假时间
   * @param {number} [time] - 刷新时间
   * @memberof HomeComponent
   */
  calcWeekend(nextWeekend, time?: number) {
    this.weekendCountdown = `0 days 00:00:00`;
    
    console.log(`
    当前时间: 周: ${moment().isoWeekday()} - ${moment().format('D 号 HH:mm:ss')} \n
    下一个放假时间:  周 ${moment(nextWeekend).isoWeekday()} - ${nextWeekend.format('D 号 HH:mm:ss')}\n
    距离放假时间； ${this.weekendCountdown}
    `)
    
    if (this.weekendCountdownTimer) clearInterval(this.weekendCountdownTimer);
    this.weekendCountdownTimer = setInterval(() => {
      // 使用时间段而不是单点时间
      const ms = nextWeekend.diff(moment());
      const duration = moment.duration(ms);
      if(ms <= 0){  // 是否已经是放假时间
        this.isHoliday = true;
        this.weekendCountdown = `0 days 00:00:00`;
        return;
      }else{
        this.isHoliday = false;
      }
      this.weekendCountdown = `${Math.floor(duration.asHours() / 24)} days ${duration.hours()}:${duration.minutes()}:${duration.seconds()}`;
    }, time || 1000)
  }

  /**
   * 响应彩蛋,函数名 ppx(皮皮虾)
   *
   * @memberof HomeComponent
   */
  tipppx() {
    this.count++;
    this.ppx.next(this.count);
  }


}
